<script setup>
  import {
    nextTick,
    onMounted,
    reactive,
    ref,
    toRaw
  } from "vue";
  import {
    useRouter
  } from "vue-router";
  import {
    pageConfig
  } from "/src/views/baseInfo/user/title/config";
  import {
    ElMessage,
    ElMessageBox
  } from "element-plus";

  const emit = defineEmits(['openViewForm', 'openEditForm'])
  const props = defineProps({
    listApi: {
      type: Function
    },
    statusApi: {
      type: Function
    },
    deleteApi: {
      type: Function
    },
    batchApi: {
      type: Function
    },
    tableColumn: {
      type: Array
    },
    pageConfig: {
      type: Object
    },
    tableConfig: {
      type: Object
    },
  })
  const router = useRouter();
  const queryFormRef = ref()
  const formInline = reactive({
    status: "0"
  })
  const totalList = ref({})
  const tableData = ref([])
  const total = ref(0)
  const currentPage = ref(1)
  const pageSize = ref(10)
  const multipleSelection = ref([])
  const loading = ref(false)
  const handleSizeChange = (val) => {
    pageSize.value = val;
    getData();
  }
  const handleCurrentChange = (val) => {
    currentPage.value = val;
    getData();
  }
  onMounted(() => {
    nextTick(() => {
      getData();
    })
  })

  const openViewForm = (row) => {
    emit("openViewForm", row)
  }
  const openEditForm = (row) => {
    if (props.tableConfig.editBtnPath) {
      router.push(props.tableConfig.editBtnPath + "?id=" + row.id)
    } else {
      emit("openEditForm", row)
    }
  }
  
  //敏感
  const getNum=(num)=>{
return num.substr(0, 3)+"****"+num.substr(num.length-4)
  }
  const updateStatus = (id, status) => {
    ElMessageBox.confirm(
      '此操作可能会影响到医生开方，请谨慎操作',
      '警告提示', {
        confirmButtonText: '继续执行',
        cancelButtonText: '取消',
        type: 'warning',
      }
    ).then(() => {
      const options = {
        status: status === 1 ? 2 : 1
      }
      if (props.tableConfig.isBatchId) {
        options.ids = [id]
      } else {
        options.id = id
      }
      props.statusApi({
        ...options
      }).then(() => {
        getData();
      })
    }).catch(() => {

    })
  }

  const deleteStatus = (id) => {
    ElMessageBox.confirm(
      '是否确定删除该条数据',
      '警告提示', {
        confirmButtonText: '继续执行',
        cancelButtonText: '取消',
        type: 'warning',
      }
    ).then(() => {
      props.deleteApi({
        id: id,
      }).then(() => {
        getData();
      })
    }).catch(() => {

    })
  }



  const resetForm = (formEl) => {
    if (!formEl) return
    console.log(formEl)
    formEl.resetFields()
    getData()
  };

  const resetFormParent = () => {
    resetForm(queryFormRef.value)
  }

  const screenClick = () => {
    console.log('submit!', toRaw(formInline))
    getData();
  }


  const getData = async () => {
    loading.value = true
    const options = {
      ...formInline
    }
    options.current_page = currentPage.value;
    options.per_page = pageSize.value;
    if (options.status === "0") {
      options.status = undefined
    }
    const result = await props.listApi({
      ...options
    });
    tableData.value = result.data.data
    total.value = result.data.total_number
    totalList.value = result.data
    loading.value = false
  }

  const handleSelectionChange = (val) => {
    multipleSelection.value = val
  }

  const batchStatus = (status) => {
    if (multipleSelection.value.length === 0) {
      ElMessage.error("请选择药品");
    }
    props.batchApi({
      ids: multipleSelection.value.map(item => item.id),
      status
    })
    ElMessage.success("操作成功");
    getData()
  }

  defineExpose({
    resetFormParent,
    formInline
  })
</script>

<template>
  <el-form :inline="true" :model="formInline" class="formALL" ref="queryFormRef">
    <el-form-item v-for="(s, sk) in tableColumn.filter(item=>item.isSearch)" :key="sk" :prop="s.prop">
      <el-input v-if="s.formType === 'input'" style="width: 180px;" v-model="formInline[s.prop]" :placeholder="s.label"
        clearable />
      <el-select v-if="['radio'].includes(s.formType)" v-model="formInline[s.prop]" style="width: 180px;"
        :placeholder="s.label">
        <el-option v-for="(sel, selKey) in Object.keys(s.enum)" :key="selKey" :label="s.enum[sel]" :value="sel" />
      </el-select>
      <el-select v-if="['select'].includes(s.formType)" v-model="formInline[s.prop]" style="width: 180px;"
        :placeholder="s.label">
        <el-option v-for="(sel, selKey) in s.asyncSelData" :key="selKey" :label="sel.name" :value="sel.id" />
      </el-select>
    </el-form-item>

    <el-form-item>
      <el-button type="primary" @click="screenClick">筛选</el-button>
      <el-button @click="resetForm(queryFormRef)" :disabled="loading">重置</el-button>
      <slot name="addBtn"></slot>
    </el-form-item>


  </el-form>

  <div class="mb-15" v-if="tableConfig.buttons.includes('batchStatus')">
    <el-button type="primary" @click="batchStatus(1)" :disabled="loading">批量上架</el-button>
    <el-button type="primary" @click="batchStatus(2)" :disabled="loading">批量下架</el-button>
  </div>

  <div class="mb-15" v-if="tableConfig.total">
    <span class="font-14 txt-color-65 mr-15" v-for="(t, tk) in tableConfig.total"
      :key="tk">{{ t.label }}：{{ totalList[t.prop] }}</span>
  </div>

  <el-table :data="tableData" @selection-change="handleSelectionChange" v-loading="loading" style="width: 100%">
    <el-table-column type="selection" width="55" v-if="tableConfig.selection"> </el-table-column>
    <el-table-column v-for="(t, tk) in tableColumn.filter(item=>item.isTable)" :key="tk" :prop="t.prop" :label="t.label"
      :fixed="t.fixed" min-width="150">
    <template #default="scope" v-if="t.enum">
        {{t.enum[scope.row[t.prop]]}}
      </template>
      <template #default="scope" v-if="t.isPrivacy">
         {{getNum(scope.row[t.prop])}}
       </template>
      <template #default="scope" v-if="t.asyncSelData">
        {{ t.asyncSelData.find(i=>i.id === scope.row[t.prop])?.name
      || t.asyncSelData.find(i=>i.id === scope.row[t.prop])?.value }}
      </template>
      <template #default="scope" v-if="t.formType === 'imageAvatar'">
        <el-image v-if="scope.row[t.prop]" style="width: 40px; height: 40px" :src="scope.row[t.prop]" :zoom-rate="1.2"
          :max-scale="4" :min-scale="0.2" :preview-src-list="[scope.row[t.prop]]" :initial-index="4" fit="cover"
          :preview-teleported="true" />
      </template>
    </el-table-column>
    <el-table-column fixed="right" label="操作" width="160">
      <template #default="scope">
        <!-- <el-button v-if="tableConfig.buttons.includes('view') && scope.row.status === 1|| (tableConfig.editBtnShow)" link type="primary"
          @click="openViewForm(scope.row)">查看</el-button>
        <el-button v-if="tableConfig.buttons.includes('edit') && (scope.row.status === 2 || tableConfig.editBtnShow)"
          link type="primary" @click="openEditForm(scope.row)">编辑</el-button>
        <el-button v-if="tableConfig.buttons.includes('status') && scope.row.status === 1" link type="primary"
          @click="updateStatus(scope.row.id, scope.row.status)">{{ tableConfig.statusText ? tableConfig.statusText[1] : "停用" }}</el-button>
        <el-button v-if="tableConfig.buttons.includes('status') && scope.row.status === 2" link type="primary"
          @click="updateStatus(scope.row.id, scope.row.status)">{{ tableConfig.statusText ? tableConfig.statusText[0] : "启用" }}</el-button>
        <el-button v-if="tableConfig.buttons.includes('delete')" link type="primary"
          @click="deleteStatus(scope.row.id)">删除</el-button>
          <el-button v-if="tableConfig.buttons.includes('store')" link type="primary"
            @click="openViewForm(scope.row)">药品管理</el-button> -->
        <el-dropdown trigger="click" class="rightButton">
          <div class="el-dropdown-link">
            操作<img src="/src/assets/bottomIcon.png" class="rightIcon" />
          </div>
          <template #dropdown>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item
                v-if="tableConfig.buttons.includes('view') && scope.row.status === 1 || tableConfig.editBtnShow"
                @click="openViewForm(scope.row)">查看</el-dropdown-item>
              <el-dropdown-item
                v-if="tableConfig.buttons.includes('edit') && (scope.row.status === 2 || tableConfig.editBtnShow)"
                @click="openEditForm(scope.row)">编辑</el-dropdown-item>
              <el-dropdown-item v-if="tableConfig.buttons.includes('status') && scope.row.status === 1"
                @click="updateStatus(scope.row.id, scope.row.status)">{{ tableConfig.statusText ? tableConfig.statusText[1] : "停用" }}</el-dropdown-item>
              <el-dropdown-item v-if="tableConfig.buttons.includes('status') && scope.row.status === 2"
                @click="updateStatus(scope.row.id, scope.row.status)">{{ tableConfig.statusText ? tableConfig.statusText[0] : "启用" }}</el-dropdown-item>
              <el-dropdown-item v-if="tableConfig.buttons.includes('delete')"
                @click="deleteStatus(scope.row.id)">删除</el-dropdown-item>
              <el-dropdown-item v-if="tableConfig.buttons.includes('store')"
                @click="openViewForm(scope.row)">药品管理</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </template>
    </el-table-column>
  </el-table>
  <div class="demo-pagination-block">
    <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[10, 20, 50, 100]"
      :small="pageConfig.small" :disabled="pageConfig.disabled" :background="pageConfig.background"
      layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
      @current-change="handleCurrentChange" />
  </div>
</template>

<style scoped lang="scss">
  ::v-deep .el-table {
    color: #515a6e;
    font-weight: 400;
    font-size: 14px !important;
  }

  ::v-deep thead tr th .cell {
    color: #515a6e;
    font-weight: 500;

  }

  ::v-deep thead tr th {
    background: #fafafa !important;
  }

  ::v-deep tbody tr td {
    font-size: 13px !important;
  }

  // .operation ::v-deep .el-button>span {
  //   color: red !important;
  // }

  .el-form-item {
    margin-right: 12px;
  }

  .custom-card {
    width: 100%;
  }

  .buttonAll {
    display: flex;
    justify-content: flex-end;
    margin-bottom: 20px;
  }

  .el-card {
    box-shadow: none;
  }

  .table-container {
    overflow-x: auto;
  }

  .upload-demo {
    display: flex;

    >* {
      position: relative;
      flex: 1;
      padding: 5px 20px;
      margin: 10px;
      background-color: white;
    }
  }

  .demo-pagination-block {
    margin: 20px 0;
    display: flex;
    justify-content: center;
  }

  .demo-pagination-block+.demo-pagination-block {
    margin-top: 10px;
  }

  .demo-pagination-block .demonstration {
    margin-bottom: 16px;
  }

  .el-dropdown-link {
    color: #409eff;
    font-size: 14px;
  }

  .rightButton {
    width: 100%;
    margin: 0 auto;
    display: flex;
    justify-content: center;

    .rightIcon {
      width: 20px;
      height: 20px;
    }
  }

  .rightButton ::v-deep .el-dropdown-link {
    display: flex;
    align-items: center;
  }


</style>